package com.yydm.serviceacls.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yydm.commonutils.R;
import com.yydm.serviceacls.dto.UserDto;
import com.yydm.serviceacls.entity.User;
import com.yydm.serviceacls.entity.UserRole;
import com.yydm.serviceacls.service.UserRoleService;
import com.yydm.serviceacls.service.UserService;
import io.swagger.annotations.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 员工
 */
@RestController
@RequestMapping("/acl/user")
@ApiModel(value = "员工用户操作层")
public class UserController {

    @Autowired
    private UserService userServer;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    /**
     * 用户分页操作
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/employees")
    @ApiOperation(value = "用户分页+模糊查询")
    public R employees(int page, int pageSize, String name) {
        Page<User> pages = new Page<>(page, pageSize);
        Page<UserDto> pageDto = new Page<>();
        LambdaQueryWrapper<User> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
        objectLambdaQueryWrapper.like(!StringUtils.isEmpty(name), User::getUsername, name);
        userServer.page(pages, objectLambdaQueryWrapper);
        BeanUtils.copyProperties(pages, pageDto, "records");
        List<UserDto> collect = pages.getRecords().stream().map(item -> {
            UserDto userDto = new UserDto();
            BeanUtils.copyProperties(item, userDto);
            Long id = item.getId();
            LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserRole::getUser_id, id);
            List<UserRole> list = userRoleService.list(queryWrapper);
            System.out.println(list);
            if (list != null) {
                List<Long> collect1 = list.stream().map(ite -> {
                    Long role_id = ite.getRole_id();
                    return role_id;
                }).collect(Collectors.toList());
                userDto.setRole(collect1);
            }
            return userDto;
        }).collect(Collectors.toList());
        pageDto.setRecords(collect);
        return R.ok().data("pageDto",pageDto);
    }

    /**
     * 用户删除操作
     *
     * @param id
     * @return
     */
    @DeleteMapping("/remove")
    @ApiOperation(value = "用户删除")
    @ApiImplicitParam(paramType = "query", name = "id", value = "用户id", required = true)
    public R userRemove(Long id) {
        System.out.println(id);
        boolean b = userServer.removeById(id);
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUser_id, id);
        boolean remove = userRoleService.remove(queryWrapper);
        if (b != true && remove != true) {
            return R.error().message("删除失败");
        }
        return R.ok().message("删除成功");
    }

    /**
     * 用户增加操作
     *
     * @param user
     * @return
     */
    @PostMapping("/save")
    @ApiOperation(value = "用户增加")
    @ApiImplicitParam(paramType = "body", name = "user", value = "增加用户信息", required = true)
    public R saveUser(@RequestBody User user) {
        if (user != null) {
            String encode = passwordEncoder.encode("1234");
            user.setPassword(encode);
            user.setImage("666.jpg");
            userServer.save(user);
            return R.ok().message("增加成功");
        } else {
            return R.error().message("删除失败");
        }

    }

    /**
     * 用户更新操作
     *
     * @param user
     */
    @PutMapping("/updateUser")
    @ApiOperation(value = "用户更新")
    @ApiImplicitParam(paramType = "body", name = "user", value = "要更新用户的id和更新的信息", required = true)
    public R updateUser(@RequestBody User user) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(User::getId, user.getId());
        boolean update = userServer.update(user, queryWrapper);
        if (update) {
            return R.ok().message("修改成功");
        }
        return R.error().message("修改失败");

    }

    /**
     * 用户更新和删除角色
     *
     * @param userDto
     * @return
     */
    @PutMapping("/userAndRole")
    @ApiOperation(value = "用户更新和删除角色")
    @ApiImplicitParam(paramType = "body", name = "userDto", value = "当前角色的数组", required = true)
    public R userAndRole(@RequestBody UserDto userDto) {
        System.out.println(userDto);
        LambdaQueryWrapper<UserRole> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserRole::getUser_id, userDto.getId());
        List<UserRole> list1 = userRoleService.list(wrapper);
        if (list1 == null || list1.size() == 0) {
            for (Long rol : userDto.getRole()) {
                UserRole ur = new UserRole();
                ur.setUser_id(userDto.getId());
                ur.setRole_id(rol);
                boolean save = userRoleService.save(ur);
            }
        }
        for (UserRole urs : list1) {
            List<Long> role = userDto.getRole();
            for (Long rol : role) {
                LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserRole::getUser_id, userDto.getId());
                queryWrapper.eq(UserRole::getRole_id, rol);
                List<UserRole> list = userRoleService.list(queryWrapper);
                if (list == null || list.size() == 0) {
                    UserRole ur = new UserRole();
                    ur.setUser_id(userDto.getId());
                    ur.setRole_id(rol);
                    boolean save = userRoleService.save(ur);
                }
                if (urs.getRole_id() != rol) {
                    LambdaQueryWrapper<UserRole> objectLambdaQueryWrapper = new LambdaQueryWrapper<>();
                    objectLambdaQueryWrapper.eq(UserRole::getUser_id, urs.getUser_id());
                    objectLambdaQueryWrapper.eq(UserRole::getRole_id, urs.getRole_id());
                    userRoleService.remove(objectLambdaQueryWrapper);
                }
            }
        }
        return R.ok().message("操作成功");
    }

}
